#!/usr/bin/env python
#coding:utf-8
# Author:   --<>
# Purpose:
# Created: 2010-01-08

import re
import urllib,urllib2

import simplejson as json
import yaml
from PyQt4 import QtCore, QtGui
from xml.dom import minidom


class UrlOpener(urllib.FancyURLopener):
    version = "py-gtranslate/1.0"

class InvalidLanguage(Exception): pass

base_uri = "http://ajax.googleapis.com/ajax/services/language/translate"
default_params = {'v': '1.0'}
langs = yaml.load(file('langs.yml', 'r').read())


def gtranslate(src, to, phrase,cbk):
    src = langs.get(src, src)
    to = langs.get(to, to)
    if not src in langs.values() or not to in langs.values():
        raise InvalidLanguage("%s=>%s is not a valid translation" % (src, to))

    args = default_params.copy()
    args.update({
        'langpair': '%s%%7C%s' % (src, to),
        'q': urllib.quote_plus(phrase),
    })
    argstring = '%s' % ('&'.join(['%s=%s' % (k,v) for (k,v) in args.iteritems()]))
    resp = json.load(UrlOpener().open('%s?%s' % (base_uri, argstring)))
    try:
        return cbk({'content':resp['responseData']['translatedText']})
    except:
        # should probably warn about failed translation
        cbk({'content':phrase})

def gtranslateAll(src, to, phrase,cbk):
    if len(phrase) > 500:
        cq = phrase[0:499]
        rs = phrase[500:len(phrase)]
        gtranslate(src,to,cq,cbk)
        QtGui.QApplication.processEvents()
        gtranslateAll(src,to,rs,cbk)
    else:
        gtranslate(src,to,phrase,cbk)


def dictcntranslate(src, to, phrase,cbk):
    from urllib2 import URLError
    params = {"utf8":"true","q":urllib.quote_plus(phrase)}
    data = urllib.urlencode(params)
    req = urllib2.Request("http://dict.cn/ws.php", data)
    try:
        result = urllib2.urlopen(req)
        QtGui.QApplication.processEvents()
        xmldoc = minidom.parseString(result.read())
        key = xmldoc.getElementsByTagName('key')[0].firstChild.data
        audio = xmldoc.getElementsByTagName('audio')[0].firstChild.data
        pron = xmldoc.getElementsByTagName('pron')[0].firstChild.data
        defs = xmldoc.getElementsByTagName('def')[0].firstChild.data
        sents = xmldoc.getElementsByTagName('sent')
        sentls = []
        for sent in sents:
            orig = sent.childNodes[0].firstChild.data
            trans = sent.childNodes[1].firstChild.data
            sentls.append("%s<br>%s<br>"%(orig,trans))

            
        vo = {'audio':audio,'content':'%s [%s]<br>%s<br>%s'%(key,pron,defs,"".join(sentls))}
        cbk(vo)
    except URLError, e:
        print e.reason
        print e.code
        cbk({'content':e.read()})




apis = {u"google-api":gtranslateAll,"dict.cn":dictcntranslate}

if __name__ == "__main__":
    def cbk(m):
        print m

    ss = """
Flash and other Non-Javascript Environments
For Flash developers, and those developers that have a need to access the AJAX Language API from other Non-JavaScript

    """
    #gtranslateAll('en',"zh-CN",ss,cbk)
    dictcntranslate(None,None,'word',cbk)










